package com.zen.lon.open.remote.context;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;

/**
 * 代理工厂bean上下文的support
 *
 * @author ZonLen since on 2021/7/1 下午11:05
 */
public abstract class AbstractFactoryBeanContextSupport implements FactoryBeanContextAware,
    BeanDefinitionRegistryPostProcessor {

  private static final String FACTORY_BEAN_CONTEXT_BEAN_NAME = "factoryBeanContext";

  /**
   * 注册 FactoryBeanContext到spring中
   */
  @Override
  public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry)
      throws BeansException {
    if (registry.containsBeanDefinition(FACTORY_BEAN_CONTEXT_BEAN_NAME)) {
      return;
    }
    BeanDefinitionBuilder builder = BeanDefinitionBuilder
        .genericBeanDefinition(FactoryBeanContext.class)
        .setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE);
    registry.registerBeanDefinition(FACTORY_BEAN_CONTEXT_BEAN_NAME, builder.getBeanDefinition());
  }

  /**
   * 设置当前抽象类的方法的引用
   */
  @Override
  public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)
      throws BeansException {
    if (beanFactory.containsBean(FACTORY_BEAN_CONTEXT_BEAN_NAME)) {
      setFactoryBeanContext(beanFactory.getBean(FactoryBeanContext.class));
    }
  }
}
